import urllib2
from urllib import urlencode
import httplib2
import amara
from pprint import pprint

POST_URL = 'http://localhost:8080/blog/'
POST_SLUG = 'A Test Entry From a Test Script!'
POST_XML = """<?xml version="1.0"?>
<entry xmlns="http://www.w3.org/2005/Atom">
  <title>A Test Entry</title>
  <id>tag:2007-01-10/should-be-removed</id>
  <author>
    <name>Eric Larson</name>
    <url>http://ionrock.org/blog/</url>
    <email>ionrock@gmail.com</email>
  </author>
  <published>2007-03-25T12:55:02Z</published>
  <updated>2007-03-25T12:55:02Z</updated>
  <link rel="self" href="http://ionrock.org/blog/test-entry.atom" title="self link" />
  <link rel="edit" href="http://ionrock.org/atom/ionrock/test-entry.atom" title="edit link" />
  <link rel="alternate" href="http://ionrock.org/blog/test-entry/" title="permalink" />
  <content type="xhtml">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Today I typed some APP code...</p>
      <p>This test entry should contain the vast majority of xhtml
      code but for now it is simply two paragraphs</p>
    </div>
  </content>
</entry>"""


class APPClient(object):
    def __init__(self, baseurl=None):
        if baseurl:
            self.baseurl = baseurl
        self.h = httplib2.Http('.cache')
        
    def post_entry(self, url, entry, slug):
        resp, content = self.h.request(url, "POST", body=entry,
            headers={'Content-type' : 'text/xml', 'slug' : slug })
        return (resp, content)

    def get_entry(self, url):
        resp, content = self.h.request(url, "GET")
        return (resp, content)

    def put_entry(self, url, entry):
        resp, content = self.h.request(url, "PUT", body=entry,
            headers={'Contetnt-type' : 'application/atom+xml;type=entry'} )
        return (resp, content)

if __name__ == '__main__':
    # do POST
    client = APPClient()
    (resp, content) = client.post_entry(POST_URL, POST_XML, POST_SLUG)

    # Get location header
    pprint(resp)
    entry_loc = resp['location']
    print "Entry created at '%s'" % entry_loc
    if not entry_loc.startswith('http'):
        entry_loc = ''.join([POST_URL.rstrip('/'), entry_loc])
        print "Getting: '%s'" % entry_loc
    (resp, content) = client.get_entry(entry_loc)

    doc = amara.parse(content)
    doc.entry.title = unicode('A changed title')
    print "Changed title to '%s'" % 'A changed title'

    # do PUT
    (resp, content) = client.put_entry(entry_loc, doc.xml(indent=True))
    print resp
    print content
